package cn.qingyun.gis.modules.enterprise.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;

@Slf4j
public class SyncTool {
    private SyncTool() {
        throw new IllegalStateException("Utility class");
    }

    @SneakyThrows
    public static void doSync(int countDown, IntConsumer consumer) {
        final ExecutorService executorService = Executors.newFixedThreadPool(6);

        CountDownLatch countDownLatch = new CountDownLatch(countDown); //同步工具类
        for (int i = 1; i < countDown + 1; i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    consumer.accept(finalI);
                } catch (Exception e) {
                    log.error("线程执行错误", e);
                }

                countDownLatch.countDown();
            });
        }
        log.info("SyncTool 等待线程结束 {}", countDown);
        boolean awaited = countDownLatch.await(120, TimeUnit.MINUTES);
        log.info("SyncTool 线程执行结束 {} {}", countDown, awaited);
    }
}
